<?php
class LoginController extends AppController
{
	var $autoRender = true;
    var $uses = array('Users','User_expand');
    var $layout = 'default';
    
    function index($type='')
    {
    	if(!isset($_SESSION["account"]))
    	{
	    	switch($type)
	    	{
	    		case 'kaixin':
	    			$this->login_kaixin();
	    			break;
	    		case 'qq':
	    			$this->login_qq();
	    			break;
	    		case 'sina':
	    			$this->login_sina();
	    			break;
	    		case 'renren':
	    			$this->login_renren();
	    			break;			
	    		default:
	    			$this->set("error_msg",'');
	    			$this->render('login');		
	    	}
    	}else{
    		header("Location:".DOMAIN);
    	}
    }
    
 	function get_auth_code()
    {
    	@include_once( dirname(__FILE__).'/../../config/config.php' );
		header("Content-type:image/png");
		
		$img_height = 20;
		$img_width = 60;
		$im = @imagecreate( $img_width, $img_height );
		$background_color = imagecolorallocate( $im, 255, 255, 255 );
		$text_color = imagecolorallocate( $im, rand( 1, 121 ), rand( 1, 121 ), rand( 1, 121 ) );
		
		for($i=1;$i<100;$i++)
		{
			if ( $i % 2 == 0 )
			{
				$disturb_str = '+';
			}
			else
			{
				$disturb_str = '*';
			}
			imagestring( $im, 1, mt_rand( 1, $img_width ), mt_rand( 1, $img_height ), $disturb_str,
			imageColorAllocate( $im, mt_rand( 121, 255 ), mt_rand( 121, 255 ), mt_rand( 121, 255 ) ) );
		}
		
		while( ( $num = rand() % 10000 ) < 1000 );
		{
		}
		$_SESSION['login_check_code'] = $num;
		//echo $_SESSION['check_code'];
		imagestring( $im, 4, 15, 2, $num, $text_color );
		imagepng( $im );
		imagedestroy( $im );
  	  	exit;
    }
    
	function check_code($check_code)
    {
    	if($check_code!=$_SESSION['login_check_code'])
    	{
    		echo json_encode(array('ret'=>1,'msg'=>'验证码错误'));
    		exit;	
    	}else{
    		echo json_encode(array('ret'=>0,'msg'=>'ok'));
    		exit;
    	}
    }
    
    function login()
    {
    	$account = $this->params["form"]["account"];
    	$pwd = md5($this->params["form"]["pwd"]);
    	$login_check_code = $this->params["form"]["check_code"];
    	
    	if($account=='')
    	{
    		$this->set("error_msg",'未输入用户名');
    		$this->render('login');
    		exit;
    	}
    	
    	if($pwd=='')
    	{
    		$this->set("error_msg",'密码不能为空');
    		$this->render('login');
    		exit;
    	}
    	
    	if($login_check_code!=$_SESSION['login_check_code'])
    	{
    		$this->set("error_msg",'验证码错误');
    		$this->render('login');
    		exit;
    	}
    	
    	$users = $this->Users->findAll("account = '$account' and pwd='$pwd'");
    	if(count($users)==1)
    	{
    		$_SESSION["user_id"] = $users[0]["Users"]["id"];
    		$_SESSION["account"] = $users[0]["Users"]["account"];
    		$_SESSION["nick_name"] =  $users[0]["Users"]["nick_name"];
    		$_SESSION['login_type'] = 'huanxinzu';
    		header("Location:".DOMAIN);
    	}else{
    		$this->set("error_msg",'登录名或密码错误');
    		$this->render('login');
    		exit;
    	}
    }
    
    function login_kaixin()
    {
    	include_once(SDK."kaixin/config.php");
		include_once(SDK."kaixin/KxApiBase.class.php");
		$_SESSION['login_type'] = 'kaixin';
		$o = new KxApiBase( WB_AKEY , WB_SKEY );
		
		//state参数用于防止CSRF攻击，授权成功后回调时会原样返回
		$_SESSION['state'] = md5(uniqid(rand(), TRUE));
		$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL, 'code', $_SESSION['state']);
		header("Location:$code_url");
    }
    
    function login_qq()
    {
    	include_once( SDK."qq_connect/API/qqConnectAPI.php");
		$_SESSION['login_type'] = 'qq';
		$qc = new QC();
		$qc->qq_login();
    }
    
    function login_renren()
    {
    	include_once( SDK."renren/config.inc.php");
		$_SESSION['login_type'] = 'renren';
		$app_id = $config->APIKey;
		$app_secret = $config->SecretKey;
		$my_url = DOMAIN;
		$_SESSION['state'] = md5(uniqid(rand(), TRUE));
		$dialog_url = "http://graph.renren.com/oauth/authorize?client_id=" 
			. $app_id."&response_type=code" ."&redirect_uri=" . urlencode($my_url) . "&state="
		    . $_SESSION['state'];
		header("Location:$dialog_url");
    }
    
    function login_sina()
    {
    	include_once( SDK."sina_weibo/config.php");
		include_once( SDK."sina_weibo/saetv2.ex.class.php");
		$_SESSION['login_type'] = 'sina';
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
		header("Location:$code_url");
    }
    
    function login_taobao()
    {
    	include_once SDK.'taobao/config.php';
		$_SESSION['login_type'] = 'taobao';
		header("location: https://oauth.taobao.com/authorize?response_type=code&client_id=21585911&redirect_uri=http://www.huanxinzu.com/sdk/taobao/oauthLogin.php");
    }
    
    function check_login()
    {
    	if(!isset($_SESSION["account"]))
    	{
		    switch ( $_SESSION['login_type'] )//根据登录的类型请求不同的第三方登录
			{
				case 'qq'://qq登录
					include_once( SDK."qq_connect/API/qqConnectAPI.php");
					$qc = new QC();
					$qc->qq_callback();
					$_SESSION['account'] = $qc->get_openid();
					break;
				case 'sina'://qq登录
					include_once( SDK."sina_weibo/config.php");
					include_once( SDK."sina_weibo/saetv2.ex.class.php");
					$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
					if (isset($_REQUEST['code'])) 
					{
						$keys = array();
						$keys['code'] = $_REQUEST['code'];
						$keys['redirect_uri'] = WB_CALLBACK_URL;
						try 
						{
							$token = $o->getAccessToken( 'code', $keys ) ;
						} 
						catch (OAuthException $e) 
						{
							
						}
					}
					if ($token) 
					{
						$_SESSION['account'] = $token['uid'];
					}
					break;
				case 'renren'://qq登录
					include_once( SDK."renren/config.inc.php");
					include_once( SDK."renren/HttpRequestService.class.php");
					$app_id = $config->APIKey;
					$app_secret = $config->SecretKey;
					$my_url = DOMAIN;
					$grant_type="authorization_code";  //支持的授权类型
					if( $_REQUEST['state'] == $_SESSION['state'] ) 
					{
		     			$token_url = "https://graph.renren.com/oauth/token?"
		       						. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
		       						. "&client_secret=" . $app_secret ."&grant_type=" . $grant_type . "&code=" . $code;
		
		     			$response = @file_get_contents($token_url);
		     			$get_params = null;
		     			parse_str($response, $params);
						if( isset( $params['access_token'] ) )
						{
							$put_params = array('fields'=>'uid,name','session_key'=>$sessionkey);//使用session_key调api的情况
							$res = $rrObj->rr_post_curl('users.getInfo', $params);//curl函数发送请求
							//$res = $rrObj->rr_post_fopen('users.getInfo', $params);//如果你的环境无法支持curl函数，可以用基于fopen函数的该函数发送请求
							//print_r($res);//输出结果
							//exit;
							$_SESSION['account'] = $params['access_token'];
						}
					}
					break;
				case 'taobao':
					break;
				case 'kaixin':
					include_once(SDK."kaixin/config.php");
					include_once(SDK."kaixin/KxApiBase.class.php");
					$o = new KxApiBase( WB_AKEY , WB_SKEY );
		
					if (isset($_REQUEST['code']) && $_REQUEST['state'] == $_SESSION['state']) 
					{
						$keys = array();
						$keys['code'] = $_REQUEST['code'];
						$keys['redirect_uri'] = WB_CALLBACK_URL;
						try 
						{
							$token = $o->getAccessToken( 'code', $keys ) ;
						} 
						catch (OAuthException $e) 
						{
							
						}
					}
					
					if ($token) 
					{
						//print_r($token["access_token"]);
						//$_SESSION['token'] = $token;
						$o = new KxApiClient(WB_AKEY, WB_SKEY, $token["access_token"]);
						$user_me = $o->users_me('uid,name,logo50');
						$_SESSION['account'] = $user_me["uid"];
					}
					break;	
				default:	
			}
			
			if(isset($_SESSION['account']))
			{
				
			}else{
				
			}
    	}
    }
    
    function login_out()
    {
    	session_destroy();
    }
}